<?php
declare (strict_types = 1);

namespace app\model;

use app\common\service\redis\PoolRedis;
use think\facade\Log;
use think\Model;
use think\model\relation\BelongsTo;

/**
 * @mixin \think\Model
 */
class AdminAttendanceSys extends Model
{

    const ATTENDANCE_CACHE_KEY = 'attendance-rules:';

    //
    const DISABLED = 0; // 禁用
    const ENABLE = 1;   // 启用
    const SCOPE_DORMITORY = 1; // 宿舍
    const SCOPE_CLASSROOM = 2; // 教室

    protected $autoWriteTimestamp = true;

    public function school(): BelongsTo {
        return $this->belongsTo('AdminSchool', 'school_id', 'id')
            ->bind(['school_name' => 'name']);
    }

    public function setStartAttr($value)
    {
        return strtotime($value);
    }
    public function getStartAttr($value)
    {
        return date('Y-m-d', $value);
    }
    public function setEndAttr($value)
    {
        return strtotime($value);
    }
    public function getEndAttr($value)
    {
        return date('Y-m-d', $value);
    }
    public function setWeeksAttr($value)
    {
        return implode(',', $value);
    }
    public function getWeeksAttr($value)
    {
        $arr = explode(',', $value);
        sort($arr);
        $arr = array_map(function ($temp) {
            return (int)$temp;
        }, $arr);
        return $arr;
    }
    public function setGradeAttr($value)
    {
        return implode(',', $value);
    }
    public function getGradeAttr($value)
    {
        $arr = explode(',', $value);
        sort($arr);
        $arr = array_map(function ($temp) {
            return $temp;
        }, $arr);
        return $arr;
    }

    public function getDateAttr($value, $data)
    {
        return  [date('Y-m-d', $data['start']), date('Y-m-d', $data['end'])];
    }

    public function setClassroomAttr($value)
    {
        return implode(',', (array)$value);
    }
    public function getClassroomAttr($value)
    {
        $arr = explode(',', (string)$value);
		if ($arr) {
			sort($arr);
			$arr = array_map(function ($temp) {
				return (int)$temp;
			}, $arr);
		}
        return $arr;
    }

    public static function onAfterWrite($model)
    {
        $key = self::ATTENDANCE_CACHE_KEY.$model->getAttr('school_id');
        $redis = PoolRedis::instance();
        $redis->delete($key);
    }
}
